package com.bestcem.xm.om.grpc.service;

import cn.hutool.core.lang.ObjectId;
import com.bestcem.bp.grpc.v1.base.Page;
import com.bestcem.xm.common.core.domain.web.RpcStatusResult;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.enums.ErrorCodeEnum;
import com.bestcem.xm.om.enums.EmailConfigTypeEnum;
import com.bestcem.xm.om.grpc.service.converter.OmUserConverter;
import com.bestcem.xm.om.grpc.v1.services.*;
import com.bestcem.xm.om.service.*;
import com.bestcem.xm.om.service.dto.EmailConfDTO;
import com.bestcem.xm.om.service.dto.RelationDTO;
import com.bestcem.xm.om.service.dto.UpdateUserBookingsDTO;
import com.bestcem.xm.om.service.dto.common.PageDTO;
import com.bestcem.xm.user.constant.CommonConstant;
import com.google.protobuf.ProtocolStringList;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.service.GrpcService;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * 描述信息
 *
 * @author xuan.yang <xuan.yang@idiaoyan.com>
 * @version v1.0
 * @date 2021/12/29 15:31
 */
@Slf4j
@GrpcService
public class OmUserGrpcService extends UserServiceGrpc.UserServiceImplBase {
    @Resource
    private OmUserService omUserService;
    @Resource
    private OmUserIndustryService omUserIndustryService;
    @Resource
    private OmPrincipalService omPrincipalService;
    @Resource
    private OmRoleService omRoleService;
    @Resource
    private UserBookingService userBookingService;
    @Resource
    private InvoiceService invoiceService;

    @Override
    public void listOmUserPermissions(ListOmUserPermissionsRequest request, StreamObserver<ListOmUserPermissionsResponse> responseObserver) {
        ListOmUserPermissionsResponse.Builder builder = ListOmUserPermissionsResponse.newBuilder();
        String userId = request.getUserId();
        ServiceResult<String> serviceResult = omUserService.getUserPermissions(userId);
        // 返回数据
        if (serviceResult.isSuccess()) {
            builder.setPermission(serviceResult.getData());
            builder.setStatus(RpcStatusResult.success());
        } else {
            String errMsg = String.format(CommonConstant.ERROR_MSG_FORMATTER, ErrorCodeEnum.SYSTEM_ERROR.getMsg(), serviceResult.getMsg());
            builder.setStatus(RpcStatusResult.error(errMsg));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void getIndustryPrincipal(GetIndustryPrincipalRequest request, StreamObserver<GetIndustryPrincipalResponse> responseObserver) {
        String industryId = request.getId();
        GetIndustryPrincipalResponse.Builder builder = GetIndustryPrincipalResponse.newBuilder();
        ServiceResult<com.bestcem.xm.om.entity.OmUser> serviceResult = omUserIndustryService.getIndustryPrincipal(industryId);
        // 返回数据
        if (serviceResult.isSuccess()) {
            com.bestcem.xm.om.entity.OmUser omUser = serviceResult.getData();
            builder.setId(omUser.getId());
            builder.setName(omUser.getRealName());
            builder.setStatus(RpcStatusResult.success());
        } else {
            String errMsg = String.format(CommonConstant.ERROR_MSG_FORMATTER, ErrorCodeEnum.SYSTEM_ERROR.getMsg(), serviceResult.getMsg());
            builder.setStatus(RpcStatusResult.error(errMsg));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void getOrgRelatedOp(GetOrgRelatedOpRequest request, StreamObserver<GetOrgRelatedOpResponse> responseObserver) {
        GetOrgRelatedOpResponse.Builder builder = GetOrgRelatedOpResponse.newBuilder();
        String orgId = request.getOrgId();
        ServiceResult<RelationDTO> serviceResult = omPrincipalService.getOrgRelatedOp(orgId);
        // 返回数据
        if (serviceResult.isSuccess()) {
            RelationDTO relationDTO = serviceResult.getData();
            builder.setPrincipalOp(relationDTO.getId())
                    .setPrincipalOpName(relationDTO.getName());
            if (!CollectionUtils.isEmpty(relationDTO.getRelationList())) {
                builder.addAllRelatedOps(relationDTO.getRelationList());
            }
            builder.setStatus(RpcStatusResult.success());
        } else {
            String errMsg = String.format(CommonConstant.ERROR_MSG_FORMATTER, ErrorCodeEnum.SYSTEM_ERROR.getMsg(), serviceResult.getMsg());
            builder.setStatus(RpcStatusResult.error(errMsg));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void createOrgRelatedOp(CreateOrgRelatedOpRequest request, StreamObserver<CreateOrgRelatedOpResponse> responseObserver) {
        CreateOrgRelatedOpResponse.Builder builder = CreateOrgRelatedOpResponse.newBuilder();
        String orgId = request.getOrgId();
        String principalOp = request.getPrincipalOp();
        ProtocolStringList relatedOpsList = request.getRelatedOpsList();
        List<String> relates = new ArrayList<>(relatedOpsList);
        ServiceResult<Void> serviceResult = omPrincipalService.createOrgRelatedOp(orgId, principalOp, relates);
        // 返回数据
        if (serviceResult.isSuccess()) {
            builder.setStatus(RpcStatusResult.success());
        } else {
            String errMsg = String.format(CommonConstant.ERROR_MSG_FORMATTER, ErrorCodeEnum.SYSTEM_ERROR.getMsg(), serviceResult.getMsg());
            builder.setStatus(RpcStatusResult.error(errMsg));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void updateOrgRelatedOp(UpdateOrgRelatedOpRequest request, StreamObserver<UpdateOrgRelatedOpResponse> responseObserver) {
        UpdateOrgRelatedOpResponse.Builder builder = UpdateOrgRelatedOpResponse.newBuilder();
        String orgId = request.getOrgId();
        String principalOp = request.getPrincipalOp();
        ProtocolStringList relatedOpsList = request.getRelatedOpsList();
        List<String> relates = new ArrayList<>(relatedOpsList);
        ServiceResult<Void> serviceResult = omPrincipalService.updateOrgRelatedOp(orgId, principalOp, relates);
        // 返回数据
        if (serviceResult.isSuccess()) {
            builder.setStatus(RpcStatusResult.success());
        } else {
            String errMsg = String.format(CommonConstant.ERROR_MSG_FORMATTER, ErrorCodeEnum.SYSTEM_ERROR.getMsg(), serviceResult.getMsg());
            builder.setStatus(RpcStatusResult.error(errMsg));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void listByPrincipalOps(ListByPrincipalOpsRequest request, StreamObserver<ListByPrincipalOpsResponse> responseObserver) {
        ListByPrincipalOpsResponse.Builder builder = ListByPrincipalOpsResponse.newBuilder();
        String name = request.getName();
        ServiceResult<List<String>> serviceResult = omPrincipalService.listIdsByName(name);
        // 返回数据
        if (serviceResult.isSuccess()) {
            builder.addAllOrgIds(serviceResult.getData());
            builder.setStatus(RpcStatusResult.success());
        } else {
            String errMsg = String.format(CommonConstant.ERROR_MSG_FORMATTER, ErrorCodeEnum.SYSTEM_ERROR.getMsg(), serviceResult.getMsg());
            builder.setStatus(RpcStatusResult.error(errMsg));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void getOmUser(GetOmUserRequest request, StreamObserver<GetOmUserResponse> responseObserver) {
        GetOmUserResponse.Builder builder = GetOmUserResponse.newBuilder();
        String userId = request.getId();
        ServiceResult<com.bestcem.xm.om.grpc.v1.services.OmUser> serviceResult = omUserService.getGrpcUserById(userId);
        // 返回数据
        if (serviceResult.isSuccess()) {
            builder.setStatus(RpcStatusResult.success());
            builder.setOmUser(serviceResult.getData());
        } else {
            String errMsg = String.format(CommonConstant.ERROR_MSG_FORMATTER, ErrorCodeEnum.SYSTEM_ERROR.getMsg(), serviceResult.getMsg());
            builder.setStatus(RpcStatusResult.error(errMsg));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void listOmUsers(ListOmUsersRequest request, StreamObserver<ListOmUsersResponse> responseObserver) {
        OmUser omUser = request.getOmUser();
        ListOmUsersResponse.Builder builder = ListOmUsersResponse.newBuilder();
        ServiceResult<List<OmUser>> serviceResult = omUserService.listOmUsers(omUser);
        // 返回数据
        if (serviceResult.isSuccess()) {
            builder.setStatus(RpcStatusResult.success());
            builder.addAllOmUsers(serviceResult.getData());
        } else {
            String errMsg = String.format(CommonConstant.ERROR_MSG_FORMATTER, ErrorCodeEnum.SYSTEM_ERROR.getMsg(), serviceResult.getMsg());
            builder.setStatus(RpcStatusResult.error(errMsg));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void listUserIndustries(ListUserIndustriesRequest request, StreamObserver<ListUserIndustriesResponse> responseObserver) {
        ListUserIndustriesResponse.Builder builder = ListUserIndustriesResponse.newBuilder();
        OmUserIndustry industry = request.getIndustry();
        ServiceResult<List<OmUserIndustry>> serviceResult = omUserIndustryService.listUserIndustries(OmUserConverter.convertToIndustry(industry));
        // 返回数据
        if (serviceResult.isSuccess()) {
            builder.setStatus(RpcStatusResult.success());
            builder.addAllUserIndustries(serviceResult.getData());
        } else {
            String errMsg = String.format(CommonConstant.ERROR_MSG_FORMATTER, ErrorCodeEnum.SYSTEM_ERROR.getMsg(), serviceResult.getMsg());
            builder.setStatus(RpcStatusResult.error(errMsg));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();

    }

    @Override
    public void listOmRoles(ListOmRolesRequest request, StreamObserver<ListOmRolesResponse> responseObserver) {
        ListOmRolesResponse.Builder builder = ListOmRolesResponse.newBuilder();
        OmRole grpcRole = request.getOmRole();
        com.bestcem.xm.om.entity.OmRole omRole = OmUserConverter.convertToOmRole(grpcRole);
        ServiceResult<List<OmRole>> serviceResult = omRoleService.listRole(omRole);
        // 返回数据
        if (serviceResult.isSuccess()) {
            builder.setStatus(RpcStatusResult.success());
            builder.addAllOmRoles(serviceResult.getData());
        } else {
            String errMsg = String.format(CommonConstant.ERROR_MSG_FORMATTER, ErrorCodeEnum.SYSTEM_ERROR.getMsg(), serviceResult.getMsg());
            builder.setStatus(RpcStatusResult.error(errMsg));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();

    }

    @Override
    public void listOmPrincipals(ListOmPrincipalsRequest request, StreamObserver<ListOmPrincipalsResponse> responseObserver) {
        ListOmPrincipalsResponse.Builder builder = ListOmPrincipalsResponse.newBuilder();
        OmPrincipal grpcPrincipal = request.getOmPrincipal();
        ServiceResult<List<OmPrincipal>> serviceResult = omPrincipalService.listOmPrincipals(OmUserConverter.convertToPrincipal(grpcPrincipal));
        // 返回数据
        if (serviceResult.isSuccess()) {
            builder.setStatus(RpcStatusResult.success());
            builder.addAllOmPrincipals(serviceResult.getData());
        } else {
            String errMsg = String.format(CommonConstant.ERROR_MSG_FORMATTER, ErrorCodeEnum.SYSTEM_ERROR.getMsg(), serviceResult.getMsg());
            builder.setStatus(RpcStatusResult.error(errMsg));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void listOrgPrincipalOps(ListOrgPrincipalOpsRequest request, StreamObserver<ListOrgPrincipalOpsResponse> responseObserver) {
        ListOrgPrincipalOpsResponse.Builder builder = ListOrgPrincipalOpsResponse.newBuilder();
        ProtocolStringList orgIdsList = request.getOrgIdsList();
        Set<String> orgIds = new HashSet<>();
        if (!orgIdsList.isEmpty()) {
            orgIds.addAll(orgIdsList);
        }
        Page page = request.getPage();
        Integer currentPage = page.getPage() == 0 ? 1 : page.getPage();
        Integer size = page.getSize() == 0 ? 10 : page.getSize();
        PageDTO<Principal> pageDTO = omPrincipalService.pageByOrgIds(orgIds, currentPage, size);
        if (pageDTO.getTotal() == 0) {
            builder.setStatus(RpcStatusResult.error("没有查询到结果"));
        } else {
            builder.setStatus(RpcStatusResult.success());
            builder.setTotal(pageDTO.getTotal());
            builder.addAllPrincipals(pageDTO.getData());
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void updateBookingByOrgId(UpdateBookingByOrgIdRequest request,
                                     StreamObserver<UpdateBookingByOrgIdResponse> responseObserver) {
        UpdateBookingByOrgIdResponse.Builder builder = UpdateBookingByOrgIdResponse.newBuilder();
        if (!ObjectId.isValid(request.getOrgId())) {
            String errMsg = String.format(CommonConstant.ERROR_MSG_FORMATTER, ErrorCodeEnum.PARAM_ERROR.getMsg(), "组织id格式不对");
            builder.setStatus(RpcStatusResult.error(errMsg));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        UpdateUserBookingsDTO updateUserBookingsDTO = new UpdateUserBookingsDTO();
        updateUserBookingsDTO.setOrgId(request.getOrgId());
        updateUserBookingsDTO.setCompanyName(request.hasCompanyName() ? request.getCompanyName() : null);
        updateUserBookingsDTO.setIndustryId(request.hasIndustryId() ? request.getIndustryId() : null);
        updateUserBookingsDTO.setPhone(request.hasPhone() ? request.getPhone() : null);
        updateUserBookingsDTO.setEmail(request.hasEmail() ? request.getEmail() : null);
        ServiceResult<Void> result = userBookingService.updateByOrgId(updateUserBookingsDTO);
        if (result.isSuccess()) {
            builder.setStatus(RpcStatusResult.success());
        } else {
            builder.setStatus(RpcStatusResult.error("没有查询到结果"));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void getOmEmailConfig(GetOmEmailConfigRequest request,
                                 StreamObserver<GetOmEmailConfigResponse> responseObserver) {
        String type = EmailConfigTypeEnum.getNameByIndex(request.getTypeValue());
        ServiceResult<EmailConfDTO> result = invoiceService.listEmailConf(type);

        GetOmEmailConfigResponse.Builder builder = GetOmEmailConfigResponse.newBuilder();
        if (result.isSuccess()) {
            EmailConfDTO emailConfDTO = result.getData();
            if (Objects.nonNull(emailConfDTO)) {
                if(Objects.nonNull(emailConfDTO.getRealEmails())){
                    builder.addAllRealEmails(emailConfDTO.getRealEmails());
                }
                if(Objects.nonNull(emailConfDTO.getTestEmails())){
                    builder.addAllTestEmails(emailConfDTO.getTestEmails());
                }
            }
            builder.setStatus(RpcStatusResult.success());
        } else {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }
}
